package controller

import (
	"jtdevice/api/device/dto"
	"jtdevice/api/device/model"
	"jtdevice/pkg/ctx"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type Alarm struct {
}

func (o *Alarm) ListHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	var data []model.Alarm
	total, _ := p.DbModelWhere(&model.Alarm{}).PreloadWith("Payload", func(db *gorm.DB) *gorm.DB {
		return db.Order("DTU ASC")
	}).Find(&data)
	for i := 0; i < len(data); i++ {
		if data[i].Payload == nil {
			continue
		}
		data[i].Flag = 1
		if data[i].Payload.Et == "" {
			data[i].Flag = 2
		}
		data[i].Et = data[i].Payload.DTU
	}
	ctx.JSONWrite(gin.H{"total": total, "data": data}, c)
}

func (o Alarm) Router(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
}
